﻿using AuthCenter.API.Application.Command.Role;
using AuthCenter.Domain;
using AuthCenter.Domain.Account;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using System.Transactions;

namespace AuthCenter.API.Application.Handler.Role
{
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;

        public UpdateRoleHandler(IBaseRepository<RoleModel> roleRepo,
                                 IBaseRepository<LogModel> logRepo,
                                 IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.logRepo = logRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = roleRepo.GetAll().FirstOrDefault(x=>x.Id == request.Id);
            if (res == null)
            {
                result.Message = "找不到此编号";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var role = roleRepo.GetAll().Where(x => x.RoleName == request.RoleName&&x.IsDel==false && x.Id != request.Id).Count();
            if (role>0)
            {
                result.Message = "已拥有该角色!";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map(request, res);
            model.UpdateDate = DateTime.Now;
            model.UpdateName = request.LoginName;

            int r = 0;
                    r = roleRepo.UpdateAsync(model).Result;
            if (r > 0)
            {
                result.Message = "修改角色信息成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "修改角色信息失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
